package dao

import (
	"github.com/go-xorm/xorm"
	"imooc.com/demo-lottery/models"
	"log"
)

type UserDayDao struct {
	engine *xorm.Engine
}

func NewUserDayDao(engine *xorm.Engine) *UserDayDao {
	return &UserDayDao{engine: engine}
}

func (d *UserDayDao) Get(id int) *models.LtUserday {
	data := &models.LtUserday{Id: id}
	ok, err := d.engine.Get(data)
	if ok && err == nil {
		return data
	} else {
		data.Id = 0
		return data
	}
}

func (d *UserDayDao) GetAll(page, size int) []models.LtUserday {
	offset := (page - 1) * size
	datalist := []models.LtUserday{}
	err := d.engine.
		Desc("id").
		Limit(size, offset).
		Find(&datalist)
	if err != nil {
		log.Println("userday_dao.GetAll error=", err)
	}
	return datalist
}

func (d *UserDayDao) Search(uid, day int) []models.LtUserday {
	datalist := make([]models.LtUserday, 0)
	err := d.engine.
		Where("uid=?", uid).
		Where("day=?", day).
		Desc("id").
		Find(&datalist)
	if err != nil {
		log.Println("userday_dao.Search error=", err)
	}
	return datalist
}

func (d *UserDayDao) Count(uid, day int) int {
	data := models.LtUserday{}
	ok, err := d.engine.
		Where("uid=?", uid).
		Where("day=?", day).
		Get(&data)
	if !ok || err != nil {
		return 0
	}
	return data.Num
}

// 结构体内某个字段若是空的，默认不会将空值更新进去mysql，要强制更新用mustCols
// mustCols: 强制要求哪些字段一定要更新
func (d *UserDayDao) Update(data *models.LtUserday, cols []string) error {
	_, err := d.engine.Id(data.Id).MustCols(cols...).Update(data)
	return err
}

func (d *UserDayDao) Create(data *models.LtUserday) error {
	_, err := d.engine.Insert(data)
	return err
}
